//
//  FileViewController.m
//  MClient
//
//  Created by  史正烨 on 09-11-14.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "FileViewController.h"
#import "MServerDAO.h"
#import "MCFunction.h"
#import "NSData+Base64.h"
#import "MClientAppDelegate.h"

#import <QuartzCore/QuartzCore.h>
#import "CustomMoviePlayer.h"


@implementation FileViewController
@synthesize fileAttribute;
@synthesize cacheFileName;

- (id)init {
	if (self = [super init]) {
		self.hidesBottomBarWhenPushed = YES;
	}
	return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
}

- (void)dealloc {
	[imgaeHtmls release];
	[fileAttribute release];
	[cacheFileName release];
    [super dealloc];
}

- (void)getDataFromServer {
	[self getDataFromServer : 1];
}

- (void)getDataFromServer : (int)page {
	currentPage = page;
	
	NSString *fileName = [self.fileAttribute objectForKey:@"fileName"];
	NSString *fileLocation = [self.fileAttribute objectForKey:@"fileLocation"];
	NSString *actionType = [self.fileAttribute objectForKey:@"actionType"];
	NSString *dataFrom = [self.fileAttribute objectForKey:@"dataFrom"];
	NSString *type = [self.fileAttribute objectForKey:@"type"] == nil?@"":[self.fileAttribute objectForKey:@"type"];
	
	NSString* szExtension = [[fileName pathExtension] lowercaseString];
	NSString *cacheFile = [MCFunction getTempFileName:szExtension];
	if ([actionType isEqualToString:@"preview"]) {
		cacheFile = [MCFunction getTempFileName:@"jpg"];
	} 
	
	self.cacheFileName = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), cacheFile];
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	[fileManager changeCurrentDirectoryPath:[NSTemporaryDirectory() stringByExpandingTildeInPath]];
	[fileManager createFileAtPath:cacheFile contents:nil attributes:nil];
	[[MServerDAO sharedInstance] downloadFileAsync:actionType
										  dataFrom:dataFrom
										  location:fileLocation
										  fileName:fileName
											  page:page
											  type:type 
									  saveLocation:cacheFileName 
										  delegate:self];
}



- (NSString *)getCharEncoding {
	return @"GBK";//
}

- (void) getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:cacheFileName];
	NSURLRequest *req = [NSURLRequest requestWithURL:fileUrl];
	[fileUrl release];
	
	NSString *fileName = [fileAttribute objectForKey:@"fileName"];
	NSRange range = [fileName rangeOfString: @"/"];
	if (range.location != NSNotFound) {
		fileName = [fileName lastPathComponent];
	}
    
    NSString* szExtension = [[cacheFileName pathExtension] lowercaseString];
    if ([szExtension isEqualToString:@"mov"]||[szExtension isEqualToString:@"avi"]) {
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(moviePlayDidFinish:) 
                                                     name:@"moviePlayDidFinish" 
                                                   object:nil];
        // Create custom movie player   
        CustomMoviePlayerViewController *moviePlayer = [[[CustomMoviePlayerViewController alloc] initWithURL:fileUrl] autorelease];//huotianjun 从临时文件目录中调出视频显示。
        
        // Show the movie player as modal
        [self presentModalViewController:moviePlayer animated:YES];//huotianjun
        
        // Prep and play the movie
        [moviePlayer readyPlayer];    //huotianjun

        return;
    }


	//解决图片下载后默认显示远小于原图的问题。
	
	if ([szExtension isEqualToString:@"png"] || [szExtension isEqualToString:@"bmp"] ||
		[szExtension isEqualToString:@"jpg"] || [szExtension isEqualToString:@"jpeg"] ||
		[szExtension isEqualToString:@"gif"] || [szExtension isEqualToString:@"psd"] ||
		[szExtension isEqualToString:@"swf"]) {
		UIImage *image = [UIImage imageWithContentsOfFile:cacheFileName];
		CGSize size = [image size];
		NSString *imageHTML = nil;
		if (size.width <= self.width && size.height <= self.height) {
			NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
			@"<html xmlns='http://www.w3.org/1999/xhtml'>"
			@"<head>"
			//@"<meta name='viewport' content='initial-scale=0.667' />"
			@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
			@"<title>%@</title>"
			@"</head>"
			@"<body><img src='%@' width='%f' height='%f'></body>"
			@"</html>";
			imageHTML  = [NSString stringWithFormat:htmlString, fileName, fileUrl, size.width, size.height];
		} else if (size.width <= self.width || size.height <= self.height) {
			NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
			@"<html xmlns='http://www.w3.org/1999/xhtml'>"
			@"<head>"
			//@"<meta  name='viewport' content='initial-scale=0.667' />"
			@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
			@"<title>%@</title>"
			@"<style type='text/css'>.customImg{%@='%f'}</style>"
			@"</head>"
			@"<body><img src='%@' class='customImg'/></body>"
			@"</html>";
			imageHTML  = [NSString stringWithFormat:htmlString, fileName, ((size.width <= self.width) ? @"width" : @"height"),
						  ((size.width <= self.width) ? size.width : size.height), fileUrl];
		} else if (size.width <= size.height) {
			NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
			@"<html xmlns='http://www.w3.org/1999/xhtml'>"
			@"<head>"
			//@"<meta name='viewport' content='initial-scale=0.667' />"
			@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
			@"<title>%@</title>"
			@"<style type='text/css'>.customImg{width='%f'}</style>"
			@"</head>"
			@"<body><img src='%@' class='customImg'/></body>"
			@"</html>";
			imageHTML  = [NSString stringWithFormat:htmlString, fileName, self.width, fileUrl];
		} else {
			NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
			@"<html xmlns='http://www.w3.org/1999/xhtml'>"
			@"<head>"
			//@"<meta name='viewport' content='initial-scale=0.667' />"
			@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
			@"<title>%@</title>"
			@"<style type='text/css'>.customImg{height='%f'}</style>"
			@"</head>"
			@"<body><img src='%@' class='customImg'/></body>"
			@"</html>";
			imageHTML  = [NSString stringWithFormat:htmlString, fileName, self.height, fileUrl];
		}
		if (imageHTML) {
			MCLog(@"imageHTML=%@", imageHTML);
			
			self.webView.scalesPageToFit = YES;
			[self.webView loadHTMLString:imageHTML baseURL:nil];
		}
		
		if(returnValue) {
			if(!hasPages) {
				NSString *contentPage = [returnValue objectForKey:@"Content-Page"];
				NSRange range = [contentPage rangeOfString: @"/"];
				if (range.location != NSNotFound) {
					NSArray *array = [contentPage componentsSeparatedByString:@"/"];
					totalPage = [(NSString *)[array objectAtIndex:1] intValue];
					
					if (totalPage > 1) {
						hasPages = YES;
						
						UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0.0f, self.height - nToolBarHeight, self.width, nToolBarHeight)];
						[pageControl setBackgroundColor:[MCUserDefaults instance].skin_navigationBarColor];
						[pageControl setNumberOfPages:totalPage];
						[pageControl setCurrentPage:0];
						pageControl.userInteractionEnabled = YES;
						pageControl.hidesForSinglePage = YES;
						[pageControl addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];
						[self.clientView addSubview:pageControl];
						[pageControl release];
						
						self.webView.frame = CGRectMake(0, 0, CGRectGetWidth(self.webView.bounds), CGRectGetHeight(self.webView.bounds) - nToolBarHeight);

						imgaeHtmls = [[NSMutableArray alloc] init];
					} else {
						hasPages = NO;
						totalPage = 0;
					}
				}
			}
			[returnValue release];
		}
		if(hasPages) {
			[imgaeHtmls addObject:imageHTML];
		}
		
	} else if ([szExtension isEqualToString:@"html"] || [szExtension isEqualToString:@"htm"] || [szExtension isEqualToString:@"txt"]) {
		NSData *htmlData = [NSData dataWithContentsOfFile:cacheFileName];  
		[self.webView loadData:htmlData MIMEType:@"text/html" textEncodingName:[self getCharEncoding] baseURL:[NSURL URLWithString:@"http://iphoneincubator.com"]]; 
		self.webView.scalesPageToFit = YES;
	}
	else {//文档附件显示
		self.title = fileName;
		self.webView.scalesPageToFit = YES;
		[self.webView loadRequest:req];
	}
}

#pragma mark ---- 按钮事件处理方法 ----
- (void) selectCancelAction: (id) sender {

	[self.navigationController popViewControllerAnimated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"fileViewControllerDidFinish" object:nil];//huotianjun 增加

}



#pragma mark ---- 视频文件播放结束事件处理方法 ----
- (void) moviePlayDidFinish:(NSNotification*)notification 
{        
 	// Remove observer
    [[NSNotificationCenter 	defaultCenter] 
     removeObserver:self
     name:@"moviePlayDidFinish" 
     object:nil];
    
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark ---- 分页预览，pagecontrol方法 ----

- (CATransition *) getAnimation:(NSString *) direction
{
    CATransition *animation = [CATransition animation];
    [animation setDelegate:self];
    [animation setType:@"reveal"];
    [animation setSubtype:direction];
    [animation setDuration:1.0f];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    return animation;
}

- (void) pageTurn: (UIPageControl *) pageControl
{
    CATransition *transition;
    int secondPage = [pageControl currentPage];
    if ((secondPage - currentPage) > 0)
        transition = [self getAnimation:@"fromRight"];
    else
        transition = [self getAnimation:@"fromLeft"];
	
	if((secondPage >= [imgaeHtmls count])) {
		[self getDataFromServer:secondPage + 1];
	} else {
		[self.webView loadHTMLString:(NSString*)[imgaeHtmls objectAtIndex:(secondPage)] baseURL:nil];
	}
	
	//[[self.webView layer] addAnimation:transition forKey:@"transitionViewAnimation"];
	currentPage = [pageControl currentPage];
	[self.webView exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
}

@end
